﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;

namespace HttpClient
{
	public class DefaultHttpResponseAdapter : HttpResponse
	{
		HttpWebResponse response;
		
		public DefaultHttpResponseAdapter(HttpWebResponse response)
		{
			this.response = response;
		}
		
		public HttpStatusCode StatusCode {
			get { return response.StatusCode; }
		}
		
		public Stream Response {
			get { return response.GetResponseStream(); }
		}
	}
	
	public class DefaultHttpClient : HTTPClient
	{		
		static CookieContainer container = new CookieContainer();
		static Dictionary<String, Action<HttpWebRequest, String>> headersActions = CreateHeadersMapping();
		
		private static Dictionary<String, Action<HttpWebRequest, String>> CreateHeadersMapping()
		{
			var actions = new Dictionary<String, Action<HttpWebRequest, String>>
			                  {{"content-type", (req, val) => req.ContentType = val}};
		    return actions;
		}
		
		public HttpResponse Execute(HttpRequest request)
		{
			var webReq = (HttpWebRequest)WebRequest.Create(request.url);
			webReq.CookieContainer = container;
			webReq.AllowAutoRedirect = request.allowAutoRedirect;
			foreach (var headerName in request.headers.Keys)
			{
				if (headersActions.ContainsKey(headerName.ToLower()))
				{
					headersActions[headerName.ToLower()](webReq, request.headers[headerName]);
				}
				else
				{
					webReq.Headers.Add(headerName, request.headers[headerName]);
				}
			}
			webReq.Method = request.method.ToString();
			if (request.userName != null)
			{
				webReq.Credentials = new NetworkCredential(request.userName, request.password);
			}
		    var content = request.Content;
			if (request.Content != null)
			{
				webReq.ContentLength = content.Length;
	            var postData = webReq.GetRequestStream();
	            postData.Write(content, 0, content.Length);
	            postData.Close();
			}

            
			return new DefaultHttpResponseAdapter((HttpWebResponse) webReq.GetResponse());
		}
	}
}
